
// #include "bits.h"
// #include "csr.h"
// #include "asm_macros.S"


#define th_mxstatus     0x7c0
#define th_mhcr         0x7c1
#define th_mcor         0x7C2



  .option arch, +xtheadint
  .option arch, +xtheadcmo
  .option norvc

  .section .text.init,"ax",@progbits
  
  .globl bl2_entrypoint
bl2_entrypoint:
	j bl2_entrypoint_real
	.word 0 // resvered
	.word 0 // BL2 MSID
	.word 0 // BL2 version
	.word 0 //
	.word 0
	.word 0
	.word 0

bl2_entrypoint_real:
  
    // atf_state_set x28, x29, ATF_STATE_BL2_ENTRY_POINT
    // debug trace ???? 
    addiw   t3, zero, 89
    slli    t3, t3, 0x19        # 0xB2000000
    lui     t4, 0x3000
    sw      t3, 132(t4)         # 3000084

    // ....
    csrw    mscratch, x0
    
    // write mtvec and make sure it sticks
    la      t0, trap_vector
    csrw    mtvec, t0

    // set mxstatus to init value
    li      t1, 0xc0638000
    csrw    th_mxstatus, t1         // th.mxstatus

    // set plic_ctrl = 1
    li      t0, 0x701FFFFC          // plic_base + 0x1FFFFC
    li      x4, 1
    sw      x4, 0(t0)

    // invalid I-cache
    li      t0, 0x33
    csrc    th_mcor, t0             // th.mcor
    li      t0, 0x11
    csrs    th_mcor, t0

    // enable I-cache
    li      t0, 0x1
    csrs    th_mhcr, t0             // th.mhcr

    # invalid D-cache
    li      t0, 0x33
    csrc    th_mcor, t0
    li      t0, 0x12
    csrs    th_mcor, t0

    # enable D-cache
    li      t0, 0x2
    csrs    th_mhcr, t0

    la      a3, __BSS_START__
    la      a4, __BSS_END__
    sub     a4, a4, a3
    beqz    a4, all_ready

bss_clear:
    sd      zero, 0(a3)
    addi    a3, a3, 8
    addi    a4, a4, -8
    bnez    a4, bss_clear

all_ready:
    lui     sp, 0x3BC19
    call    bl2_main
    j       die


    .balign 4
trap_vector:
die:
    j panic_handler
    j die


